IF OBJECT_ID('fGetSegmentRootDocument') IS NOT NULL 
BEGIN 
    DROP FUNCTION fGetSegmentRootDocument
    IF OBJECT_ID('fGetSegmentRootDocument') IS NOT NULL
        PRINT '<<< FAILED DROPPING FUNCTION fGetSegmentRootDocument >>>'
    ELSE 
        PRINT '<<< DROPPED FUNCTION fGetSegmentRootDocument >>>'
END
GO
CREATE FUNCTION dbo.fGetSegmentRootDocument
(
    @SegmentId   int = NULL
,   @IncludePath bit = 1
)
RETURNS varchar(1024)
AS
BEGIN
    DECLARE
        @Path varchar(1024)

    IF @IncludePath = 1
    BEGIN
        SELECT
            @Path = 
                CASE 
                WHEN SUBSTRING([Document].Path,1,1) = '/'
                THEN
                    '.' + [Document].Path + [Document].[FileName]
                ELSE
                    [Document].Path + [Document].[FileName]
                END
        FROM
            [Document]
        ,   Segment
        WHERE
            [Document].SegmentId = Segment.SegmentId
        AND
            [Document].SegmentId = @SegmentId
        AND
            [Document].IsActive = 1
        AND
            [Document].IsRoot = 1
    END

RETURN @Path
END
GO
GRANT EXECUTE ON fGetSegmentRootDocument TO public
GO
IF OBJECT_ID('fGetSegmentRootDocument') IS NOT NULL 
    PRINT '<<< CREATED FUNCTION fGetSegmentRootDocument >>>' 
ELSE 
    PRINT '<<< FAILED CREATING FUNCTION fGetSegmentRootDocument >>>' 
GO 